# 步骤 1: 创建备忘录类
class Memento:
    def __init__(self, state):
        self._state = state

    def get_saved_state(self):
        return self._state


# 步骤 2: 创建原发器类
class Originator:
    def __init__(self):
        self._state = ""

    def set(self, state):
        print(f"Setting state to {state}")
        self._state = state

    def save_to_memento(self):
        print(f"Saving to Memento: {self._state}")
        return Memento(self._state)

    def restore_from_memento(self, memento):
        self._state = memento.get_saved_state()
        print(f"State after restoring from Memento: {self._state}")


# 步骤 3: 创建负责人类
class Caretaker:
    def __init__(self):
        self._mementos = []

    def add_memento(self, memento):
        self._mementos.append(memento)

    def get_memento(self, index):
        return self._mementos[index]


if __name__ == '__main__':
    # 步骤 4: 使用备忘录模式
    originator = Originator()
    caretaker = Caretaker()

    originator.set("State1")
    caretaker.add_memento(originator.save_to_memento())

    originator.set("State2")
    caretaker.add_memento(originator.save_to_memento())

    originator.set("State3")
    caretaker.add_memento(originator.save_to_memento())

    # 恢复到第一个保存的状态
    originator.restore_from_memento(caretaker.get_memento(0))

'''
Setting state to State1
Saving to Memento: State1
Setting state to State2
Saving to Memento: State2
Setting state to State3
Saving to Memento: State3
State after restoring from Memento: State1
'''
